package com.sls.game.parser;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.sls.core.util.ServerDateAndTime;
import com.sls.game.dao.xinhe.XinHeAccountDAO;
import com.sls.game.dao.xinhe.XinHeChargeUnitDAO;
import com.sls.game.dao.xinhe.XinHeCompanyDAO;
import com.sls.game.dao.xinhe.XinHeGameDAO;
import com.sls.game.dao.xinhe.XinHeGameGiftDAO;
import com.sls.game.dao.xinhe.XinHeProductDAO;
import com.sls.game.pojo.xinhe.Company;
import com.sls.game.pojo.xinhe.XinHeAccount;
import com.sls.game.pojo.xinhe.XinHeChargeUnit;
import com.sls.game.pojo.xinhe.XinHeGame;
import com.sls.game.pojo.xinhe.XinHeGameGift;
import com.sls.game.pojo.xinhe.XinHeProduct;
import com.sls.game.pojo.xinhe.XinHeRespInfo;

public class ParseXinHeXml {

	private static Logger log = Logger.getLogger(ParseXinHeXml.class);

	public static XinHeRespInfo getReturnOfXinHe(String returnMsg) {
		XinHeRespInfo resInfo = new XinHeRespInfo();
		if (StringUtils.isNotBlank(returnMsg)) {
			String[] result1 = returnMsg.split("&");
			if (result1 != null && result1.length > 0) {
				for (String kv : result1) {
					String[] result2 = kv.split("=");
					if (result2 != null && result2.length > 1) {
						if ("return".equals(result2[0])) {
							resInfo.setReturnMsg(result2[1]);
						} else if ("orderNo".equals(result2[0])) {
							resInfo.setOrderNo(result2[1]);
						} else if ("xhOrder".equals(result2[0])) {
							resInfo.setXhOrder(result2[1]);
						} else if ("amount".equals(result2[0])) {
							resInfo.setAmount(result2[1]);
						} else if ("cost".equals(result2[0])) {
							resInfo.setCost(result2[1]);
						} else if ("balance".equals(result2[0])) {
							resInfo.setBalance(result2[1]);
						} else if ("sign".equals(result2[0])) {
							resInfo.setSign(result2[1]);
						} else if ("snapshot".equals(result2[0])) {
							resInfo.setSnapshot(result2[1]);
						}
					}
				}
			}
		}
		return resInfo;
	}

	@SuppressWarnings("unchecked")
	public static List<Company> getAllCompanys(String xml,
			XinHeCompanyDAO comDao) {
		Document document = null;
		Element root = null;
		List<Company> list = new ArrayList<Company>();
		// 读取XML文件,获得document对象
		try {
			document = DocumentHelper.parseText(xml);
			Company com = null;
			root = document.getRootElement();
			Iterator<Element> it = root.elementIterator();
			while (it.hasNext()) {
				com = new Company();
				Element secondEle = it.next();
				String tagName = secondEle.getName();
				if ("company".equals(tagName)) {
					Attribute idAtt = secondEle.attribute("id");
					com.setId(idAtt.getValue());
					Attribute nameAtt = secondEle.attribute("name");
					com.setName(nameAtt.getValue());
				}
				list.add(com);
				String id = com.getId();
				Company c = comDao.queryById(id);
				if(c == null){
					comDao.insert(com);
				}else{
					comDao.update(com);
				}
			}

		} catch (DocumentException e) {
			log.error("解析鑫合返回的游戏商家信息出现异常", e);
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	public static void insertProductInfo(String xml, String companyId,
			XinHeProductDAO pDao, XinHeAccountDAO aDao, XinHeGameDAO gDao,
			XinHeChargeUnitDAO cDao, XinHeGameGiftDAO ggDao) {
		Document document = null;
		Element root = null;
		try {
			document = DocumentHelper.parseText(xml);
			root = document.getRootElement();
			Attribute rootAtt = root.attribute("version");
			String version = "";
			if (rootAtt != null) {
				version = rootAtt.getValue();
			}
			Iterator<Element> it = root.elementIterator();
			while (it.hasNext()) {
				Element secondEle = it.next();
				String tagName = secondEle.getName();
				if ("productList".equals(tagName)) {
					saveProductList(pDao, secondEle, version, companyId);
				} else if ("accountTypeList".equals(tagName)) {
					saveAccountList(aDao, secondEle, version, companyId);
				} else if ("gameList".equals(tagName)) {
					saveGameList(gDao, ggDao, cDao, secondEle, version,
							companyId);
				}
			}

		} catch (DocumentException e) {
			log.error("解析鑫合返回的产品充值信息出现异常", e);
		}
	}

	@SuppressWarnings("unchecked")
	private static void saveGameGift(XinHeGameGiftDAO ggDao, Element fourEle,
			String gameId, String gameName, String version, String companyId) {
		Iterator<Element> it = fourEle.elementIterator();
		while (it.hasNext()) {
			XinHeGameGift xhgg = new XinHeGameGift();
			Element fiveEle = it.next();
			String tagName2 = fiveEle.getName();
			if ("gift".equals(tagName2)) {
				Attribute giftIdAtt = fiveEle.attribute("id");
				Attribute giftNameAtt = fiveEle.attribute("name");
				Attribute giftGSIAtt = fiveEle.attribute("gameServerId");
				xhgg.setGiftId(giftIdAtt.getValue());
				xhgg.setGiftName(giftNameAtt.getValue());
				xhgg.setServerId(giftGSIAtt.getValue());
				xhgg.setGameId(gameId);
				xhgg.setGameName(gameName);
				xhgg.setVersion(version);
				xhgg.setCompanyId(companyId);
			}
			insertOrUpdateGift(xhgg, ggDao, companyId);
		}
	}

	@SuppressWarnings("unchecked")
	private static void saveChargeUnit(XinHeChargeUnitDAO cDao,
			Element fourEle, String gameId, String gameName, String version,
			String companyId) {
		Iterator<Element> it = fourEle.elementIterator();
		while (it.hasNext()) {
			XinHeChargeUnit xhcu = new XinHeChargeUnit();
			Element fiveEle = it.next();
			String tagName2 = fiveEle.getName();
			if ("chargeUnit".equals(tagName2)) {
				Attribute chargeIdAtt = fiveEle.attribute("id");
				Attribute chargeNameAtt = fiveEle.attribute("name");
				Attribute chargeValueAtt = fiveEle.attribute("value");
				Attribute chargeGSIAtt = fiveEle.attribute("gameServerId");
				xhcu.setChargeId(chargeIdAtt.getValue());
				xhcu.setChargeName(chargeNameAtt.getValue());
				xhcu.setChargeValue(chargeValueAtt.getValue());
				xhcu.setServerId(chargeGSIAtt.getValue());
				xhcu.setGameId(gameId);
				xhcu.setGameName(gameName);
				xhcu.setVersion(version);
				xhcu.setCompanyId(companyId);
			}
			insertOrUpdateCharge(xhcu, cDao, companyId);
		}
	}

	@SuppressWarnings("unchecked")
	private static void saveGameList(XinHeGameDAO gDao, XinHeGameGiftDAO ggDao,
			XinHeChargeUnitDAO cDao, Element secondEle, String version,
			String companyId) {
		Iterator<Element> it2 = secondEle.elementIterator();
		while (it2.hasNext()) {
			Element thirdEle = it2.next();
			String tagName2 = thirdEle.getName();
			if ("game".equals(tagName2)) {
				Attribute gameIdAtt = thirdEle.attribute("id");
				Attribute gameNameAtt = thirdEle.attribute("name");
				Iterator<Element> it3 = thirdEle.elementIterator();
				while (it3.hasNext()) {
					Element fourEle = it3.next();
					String tagName3 = fourEle.getName();
					if ("gameZoneList".equals(tagName3)) {
						Iterator<Element> it4 = fourEle.elementIterator();
						if (it4.hasNext()) {
							while (it4.hasNext()) {
								Element fiveEle = it4.next();
								String tagName4 = fiveEle.getName();
								if ("gameZone".equals(tagName4)) {
									Attribute zoneIdAtt = fiveEle
											.attribute("id");
									Attribute zoneNameAtt = fiveEle
											.attribute("name");
									Iterator<Element> it5 = fiveEle
											.elementIterator();
									while (it5.hasNext()) {
										Element sixEle = it5.next();
										String tagName5 = sixEle.getName();
										if ("gameServerList".equals(tagName5)) {
											Iterator<Element> it6 = sixEle
													.elementIterator();
											if (it6.hasNext()) {

												while (it6.hasNext()) {
													XinHeGame game = new XinHeGame();
													Element sevenEle = it6
															.next();
													String tagName6 = sevenEle
															.getName();
													if ("gameServer"
															.equals(tagName6)) {
														Attribute serverIdAtt = sevenEle
																.attribute("id");
														Attribute serverNameAtt = sevenEle
																.attribute("name");
														game.setVersion(version);
														game.setCompanyId(companyId);
														game.setGameId(gameIdAtt
																.getValue());
														game.setGameName(gameNameAtt
																.getValue());
														game.setAreaId(zoneIdAtt
																.getValue());
														game.setAreaName(zoneNameAtt
																.getValue());
														game.setServerId(serverIdAtt
																.getValue());
														game.setServerName(serverNameAtt
																.getValue());
													}
													insertGame(game, gDao);
												}
											} else {
												XinHeGame game = new XinHeGame();
												game.setVersion(version);
												game.setCompanyId(companyId);
												game.setGameId(gameIdAtt
														.getValue());
												game.setGameName(gameNameAtt
														.getValue());
												game.setAreaId(zoneIdAtt
														.getValue());
												game.setAreaName(zoneNameAtt
														.getValue());
												insertGame(game, gDao);
											}
										}
									}
								}
							}
						} else {
							XinHeGame game = new XinHeGame();
							game.setVersion(version);
							game.setCompanyId(companyId);
							game.setGameId(gameIdAtt.getValue());
							game.setGameName(gameNameAtt.getValue());
							insertGame(game, gDao);
						}
					} else if ("giftList".equals(tagName3)) {
						saveGameGift(ggDao, fourEle, gameIdAtt.getValue(),
								gameNameAtt.getValue(), version, companyId);
					} else if ("chargeUnitList".equals(tagName3)) {
						saveChargeUnit(cDao, fourEle, gameIdAtt.getValue(),
								gameNameAtt.getValue(), version, companyId);
					} else if ("needAccount2".equals(tagName3)) {
						Attribute accValueAtt = fourEle.attribute("value");
						XinHeGame game = new XinHeGame();
						game.setGameId(gameIdAtt.getValue());
						game.setNeedAccount2(accValueAtt.getValue());
						gDao.update(game);
					} else if ("needRole".equals(tagName3)) {
						Attribute roleValueAtt = fourEle.attribute("value");
						XinHeGame game = new XinHeGame();
						game.setGameId(gameIdAtt.getValue());
						game.setNeedRole(roleValueAtt.getValue());
						gDao.update(game);
					}
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	private static void saveAccountList(XinHeAccountDAO aDao,
			Element secondEle, String version, String companyId) {
		Iterator<Element> it2 = secondEle.elementIterator();
		while (it2.hasNext()) {
			XinHeAccount xha = new XinHeAccount();
			xha.setVersion(version);
			xha.setCompanyId(companyId);
			Element thirdEle = it2.next();
			String tagName2 = thirdEle.getName();
			if ("accountType".equals(tagName2)) {
				Iterator<Attribute> thirdAtt = thirdEle.attributeIterator();
				while (thirdAtt.hasNext()) {
					Attribute att = thirdAtt.next();
					String attName = att.getName();
					if ("id".equals(attName)) {
						String id = att.getValue();
						xha.setAccountId(id);
					} else if ("name".equals(attName)) {
						String name = att.getValue();
						xha.setAccountName(name);
					} else if ("gameId".equals(attName)) {
						String gameId = att.getValue();
						xha.setGameIdList(gameId);
					}
				}
				insertOrUpdateAccount(xha, aDao, companyId);
			}
		}
	}

	@SuppressWarnings("unchecked")
	private static void saveProductList(XinHeProductDAO pDao,
			Element secondEle, String version, String companyId) {
		Iterator<Element> it2 = secondEle.elementIterator();
		while (it2.hasNext()) {
			XinHeProduct xhp = new XinHeProduct();
			xhp.setCompanyId(companyId);
			xhp.setVersion(version);
			Element thirdEle = it2.next();
			String tagName2 = thirdEle.getName();
			if ("product".equals(tagName2)) {
				Iterator<Attribute> thirdAtt = thirdEle.attributeIterator();
				while (thirdAtt.hasNext()) {
					Attribute att = thirdAtt.next();
					String attName = att.getName();
					if ("id".equals(attName)) {
						String id = att.getValue();
						xhp.setProductId(id);
					} else if ("name".equals(attName)) {
						String name = att.getValue();
						xhp.setProductName(name);
					} else if ("par".equals(attName)) {
						String par = att.getValue();
						xhp.setProductParvalue(par);
					} else if ("price".equals(attName)) {
						String price = att.getValue();
						xhp.setProductPrice(price);
					} else if ("rebate".equals(attName)) {
						String rebate = att.getValue();
						xhp.setRebate(rebate);
					} else if ("numberLimit".equals(attName)) {
						String numberLimit = att.getValue();
						xhp.setNumberLimit(numberLimit);
					}
				}
				insertOrUpdatePro(xhp, pDao);
			}
		}
	}

	private static void insertOrUpdatePro(XinHeProduct xhp, XinHeProductDAO pDao) {
		XinHeProduct xinhe = pDao.queryByProductId(xhp.getProductId());
		if (xinhe != null) {
			String id = xinhe.getId();
			xhp.setId(id);
			xhp.setIsAudit("0");
			xhp.setModifyTime(ServerDateAndTime.getNowDateTimeOfFormat());
			pDao.update(xhp);
		} else {
			String id = UUID.randomUUID().toString();
			xhp.setId(id);
			xhp.setIsAudit("0");
			xhp.setInsertTime(ServerDateAndTime.getNowDateTimeOfFormat());
			pDao.insert(xhp);
		}
	}

	private static void insertOrUpdateAccount(XinHeAccount xha,
			XinHeAccountDAO aDao, String companyId) {
		XinHeAccount xa = new XinHeAccount();
		xa.setCompanyId(companyId);
		xa.setAccountId(xha.getAccountId());
		XinHeAccount xinhea = aDao.queryByAccountId(xa);
		if (xinhea != null) {
			String id = xinhea.getId();
			xha.setId(id);
			aDao.update(xinhea);
		} else {
			String id = UUID.randomUUID().toString();
			xha.setId(id);
			aDao.insert(xha);
		}
	}

	private static void insertGame(XinHeGame game, XinHeGameDAO gDao) {
		XinHeGame ga = gDao.queryByAreaIdOrServerId(game);
		if (ga != null) {
			String id = ga.getId();
			game.setId(id);
			gDao.update0(game);
		} else {
			String id = UUID.randomUUID().toString();
			game.setId(id);
			gDao.insert(game);
		}
	}

	private static void insertOrUpdateCharge(XinHeChargeUnit xhcu,
			XinHeChargeUnitDAO cDao, String companyId) {
		XinHeChargeUnit xhu = new XinHeChargeUnit();
		xhu.setChargeId(xhcu.getChargeId());
		xhu.setCompanyId(companyId);
		XinHeChargeUnit xu = cDao.queryByChargeId(xhu);
		if (xu != null) {
			String id = xu.getId();
			xhcu.setId(id);
			cDao.update(xhcu);
		} else {
			String id = UUID.randomUUID().toString();
			xhcu.setId(id);
			cDao.insert(xhcu);
		}

	}

	private static void insertOrUpdateGift(XinHeGameGift xhgg,
			XinHeGameGiftDAO ggDao, String companyId) {
		XinHeGameGift xhg = new XinHeGameGift();
		xhg.setCompanyId(companyId);
		xhg.setGiftId(xhgg.getGiftId());
		XinHeGameGift xg = ggDao.queryByGiftId(xhg);
		if (xg != null) {
			String id = xg.getId();
			xhgg.setId(id);
			ggDao.update(xhgg);
		} else {
			String id = UUID.randomUUID().toString();
			xhgg.setId(id);
			ggDao.insert(xhgg);
		}

	}

}
